<?php
class Dig_Navigation
{
    protected static $_defaultType = 'cms';
    protected static $_pageTypeAliases = array('cms' => 'Dig_Navigation_Page_Dynamic' , 'static' => 'Dig_Navigation_Page_Static' , 'mvc' => 'Dig_Navigation_Page_Mvc');
    protected static $_propertiesToPass = array('label' , 'action' , 'controller' , 'module' , 'id' , 'class' , 'title' , 'active' , 'uri' , 'scope' , 'template' , 'skin');
    public static function factory (SimpleXMLElement $treeNode)
    {
        $pageArray = self::getPageArray($treeNode);
        if (is_array($pageArray)) {
            return new Zend_Navigation($pageArray);
        }
    }
    public static function getPageArray (SimpleXMLElement $treeNode, $basePath = null)
    {
        if (isset($treeNode->page)) {
            $pageArray = array();
            foreach ($treeNode->page as $node) {
                $page = array();
                $attribs = $node->attributes();
                $propertiesToPass = self::$_propertiesToPass;
                $page['uri'] = $basePath . '/' . (string) $attribs->id;
                foreach ($propertiesToPass as $property) {
                    if (isset($attribs->$property)) {
                        $page[$property] = (string) $attribs->$property;
                    }
                }
                $children = $node->children();
                if (isset($children->page)) {
                    $page['pages'] = self::getPageArray($children, $page['uri']);
                }
                $page = self::setDefaultProperties($page, $attribs);
                $pageArray[] = $page;
            }
            return $pageArray;
        } else {
            return false;
        }
    }
    public static function setDefaultProperties ($page, $attribs = null)
    {
        // label
        if (! isset($page['label'])) {
            $page['label'] = ucwords(str_replace('_', ' ', $page['id']));
        }
        $page['type'] = isset($attribs['type']) ? (string) $attribs['type'] : self::$_defaultType;
        // map digitalus types to their classes 
        $type = $page['type'];
        if (array_key_exists($type, self::$_pageTypeAliases)) {
            $page['type'] = self::$_pageTypeAliases[$type];
        }
        return $page;
    }
}
?>